import axios from "axios";

export interface OAuth2Response {
    access_token: string;
    expires_in: number;
    refresh_token: string;
    openid: string;
    scope: string;
}

export interface SnsUserInfoResponse {
    openid: string;
    nickname: string;
    sex: string;
    province: string;
    city: string;
    country: string;
    headimgurl: string;
    privilege: string[];
    unionid: string;
    language?: string;
}

export interface RefreshTokenResponse {
    access_token: string;
    expires_in: number;
    refresh_token: string;
    openid: string;
    scope: string;
}

export default class WechatOpen {
    protected appid: string;
    protected secret: string;
    constructor(appid: string, secret: string) {
        this.appid = appid;
        this.secret = secret;
    }
	/**
	 * 通过code换取access_token
	 */
    async oauth2(code: string): Promise<OAuth2Response> {
        var url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${this.appid}&secret=${this.secret}&code=${code}&grant_type=authorization_code`
        var ret = await axios.get(url)
        if (ret.data.errmsg)
            throw { no: ret.data.errcode, msg: ret.data.errmsg }
        return ret.data;
    }

    async refreshToken(refresh_token: string): Promise<RefreshTokenResponse> {
        var url = `https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=${this.appid}&grant_type=refresh_token&refresh_token=${refresh_token}`
        var ret = await axios.get(url)
        if (ret.data.errmsg)
            throw { no: ret.data.errcode, msg: ret.data.errmsg }
        return ret.data;
    }

    async snsUserInfo(access_token: string, openid: string): Promise<SnsUserInfoResponse> {
        var url = `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`
        var ret = await axios.get(url)
        if (ret.data.errmsg)
            throw { no: ret.data.errcode, msg: ret.data.errmsg }
        return ret.data;
    }

}